// #ifdef MP-WEIXIN
// import AMapWX from './amap-wx.js';
const AMapWX = require('./amap-wx.js');
console.log(AMapWX)
const amap2 = new AMapWX({ key: '89004463535a10998f02dfa22072edc9' });
// #endif

// #ifdef APP-PLUS
let AMap = null;
const loadAMapSDK = () => {
  return new Promise(resolve => {
    if (window.AMap) return resolve(window.AMap);
    
    const script = document.createElement('script');
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${require('./amap-key.js').appKey}`;
    script.onload = () => resolve(window.AMap);
    document.head.appendChild(script);
  });
};
// #endif

export default {
  // 统一定位方法
  async getLocation() {
    // #ifdef MP-WEIXIN
    return new Promise(resolve => {
      amap2.getRegeo({
        success: data => resolve({
          latitude: data[0].latitude,
          longitude: data[0].longitude
        })
      });
    });
    // #endif
    
    // #ifdef APP-PLUS
    AMap = await loadAMapSDK();
    return new Promise(resolve => {
      new AMap.Geolocation({
        enableHighAccuracy: true
      }).getCurrentPosition((status, result) => {
        resolve({
          latitude: result.position.lat,
          longitude: result.position.lng
        });
      });
    });
    // #endif
  },

  // 统一搜索周边POI
  async searchPOI(lng, lat) {
    // #ifdef MP-WEIXIN
    return new Promise(resolve => {
      amap2.getPoiAround({
        location: `${lng},${lat}`,
        success: resolve
      });
    });
    // #endif
    
    // #ifdef APP-PLUS
    return new Promise(resolve => {
      new AMap.PlaceSearch().searchNearBy('', [lng, lat], 1000, (status, result) => {
        resolve(result.poiList.pois.map(formatPOI));
      });
    });
    // #endif
  }
}

// 统一数据格式
function formatPOI(item) {
  return {
    id: item.id || '',
    name: item.name || '未知地点',
    location: item.location ? item.location : `${item.longitude},${item.latitude}`,
    distance: item.distance || 0
  }
}